package cn.icatw.gulimall.auth.controller;

import cn.icatw.common.constant.AuthServerConstant;
import cn.icatw.common.utils.HttpUtils;
import cn.icatw.common.utils.R;
import cn.icatw.gulimall.auth.feign.MemberFeignService;
import cn.icatw.common.vo.MemberRespVo;
import cn.icatw.gulimall.auth.vo.SocialUser;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * oauth2控制器
 *
 * @author icatw
 * @date 2022/3/22
 * @email 762188827@qq.com
 * @apiNote 处理社交登陆请求
 */
@Slf4j
@Controller
public class Oauth2Controller {
    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 微博 社交登陆回调
     *
     * @param code 代码
     * @return {@link String}
     * @throws Exception 异常
     */
    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        //1、根据code换取accessToken；
        //query.put("client_id", "3981568198");
        //query.put("client_secret", "66e2ec31b90ff121b34d0f5415e832c7");
        //https://api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=CODE
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "3981568198");
        map.put("client_secret", "66e2ec31b90ff121b34d0f5415e832c7");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);

        //1、根据用户授权返回的code换取access_token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());

        //处理
        if (response.getStatusLine().getStatusCode() == 200) {
            //    响应成功，获取到accessToken，json数据
            //EntityUtils.toString 将json转换为entity，再将entity转为javabean
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //    知道当前是哪个社交用户，并根据社交账号信息注册一个用户
            //1）、当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息，以后这个社交账号就对应指定的会员）
            //登录或者注册这个社交用户
            System.out.println(socialUser.getAccess_token());
            //    远程登陆
            R r = memberFeignService.oauthlogin(socialUser);
            if (r.getCode() == 0) {
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                log.info("登陆成功：用户信息{}", data.toString());
                //1、第一次使用session，命令浏览器保存卡号，JSESSIONID这个cookie
                //以后浏览器访问哪个网站就会带上这个网站的cookie
                //成功，放入session
                session.setAttribute(AuthServerConstant.LOGIN_USER, data);
                //成功
                //2、登陆成功就跳回首页
                return "redirect:http://gulimall.com";
            } else {
                //    响应失败
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            //    响应失败
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
